clear;
close all;

% Load data
load('Result_K_6.mat')

% Preallocate matrices
beta_c_quantile50 = zeros(6, 292);
beta_c_quantile25 = zeros(6, 292);
beta_c_quantile75 = zeros(6, 292);

% Titles for the factors
titles = {'MKT', 'SMB', 'HML', 'RMW', 'CMA', 'MOM'};

% Loop to calculate quantiles
for t = 1:292
    ord = betat_hat(:, 1, t) ~= 0;  % Non-zero entries
    beta_c_quantile50(:, t) = quantile(betat_hat(ord, 1:6, t), 0.5);
    beta_c_quantile25(:, t) = quantile(betat_hat(ord, 1:6, t), 0.25);
    beta_c_quantile75(:, t) = quantile(betat_hat(ord, 1:6, t), 0.75);
end

% Create the figure
figure;

% Loop through the factors and plot
for k = 1:6
    subplot(3, 2, k);  % Arrange subplots in a 3x2 grid

    % Plot the shaded region for the 25th and 75th quantiles
    shadedplot(1:292, beta_c_quantile25(k, :), beta_c_quantile75(k, :), [0.7 0.7 1], [0.7 0.7 1]);
    hold on;
    
    % Plot the median (50th quantile)
    plot(1:292, beta_c_quantile50(k, :), 'b', 'LineWidth', 2);
    
    % Add title and set font size
    title(titles{k}, 'FontSize', 14, 'FontWeight', 'bold');
    
    % Add labels and grid
  %  xlabel('Time', 'FontSize', 12);
  %  ylabel('Beta', 'FontSize', 12);
    grid on;
     set(gca,'xtick', 1:72:292,'xticklabel',num2str([1996;2002;2008;2014;2020]))
    % Set axis tight for better visualization
    ylim([-1,1.5]);
    xlim([1,292]);
    %axis tight;
end

% Improve overall figure appearance
set(gcf, 'Color', 'w');  % Set background color to white

% Export the figure to both EPS and PDF
ax = gcf;
exportgraphics(ax, 'betaplot.eps');
exportgraphics(ax, 'betaplot.pdf');

